package com.interview.javabasic.DataStructrue.HuffmanCode;/*
@李子宁
Happy,happy everyday!
冲鸭！
*/

import java.io.*;
import java.util.*;

public class HurrmanCode {
    public static void main(String[] args) {
        //测试压缩文件：
      /*  System.out.println("****************************************");
        String scrFile = "d://src.bmp";
        String dstFile = "d://dst.zip";

        zipFile(scrFile,dstFile);
        System.out.println("压缩文件ok");
        System.out.println("****************************************");

*/
        //测试解压文件：
        System.out.println("****************************************");
        String zipFile = "d://dst.zip";
        String dstFile = "d://src2.bmp";

        unZipFile(zipFile,dstFile);
        System.out.println("解压缩文件ok");
        System.out.println("****************************************");



        /*String str = "i like like like java do you like a java";
        byte[] contentBytes = str.getBytes();
        byte[] bytes = huffmanZip(contentBytes);
        System.out.println("压缩后的结果："+Arrays.toString(bytes)+"长度是："+bytes.length);


        byte[] decode = decode(humanCodes, bytes);
        System.out.println("原来的字符串："+ new String(decode) +"长度是："+decode.length);*/



        /*List<Node> nodes = getnodes(contentBytes);
        System.out.println("nodes= "+nodes);

        //创建的二叉树
        System.out.println("赫夫曼树：");
        Node huffmanTree = createHuffmanTree(nodes);
        System.out.println("前序遍历：");
        huffmanTree.preOrder();

        //测试编码显示
        Map<Byte, String> codes = getCodes(huffmanTree);
        System.out.println("生成的哈弗曼编码表： "+codes);

        byte[] zip = zip(contentBytes, humanCodes);
        System.out.println("huffmancondeBytes= "+Arrays.toString(zip));*/

    }

    //压缩文件
    public static void zipFile(String srcFile,String dstFile){
        //创建输出流
        //创建文件的输入流
        OutputStream os = null;
        ObjectOutputStream oos = null;
        FileInputStream is = null;
        try{
            is = new FileInputStream(srcFile);
            byte[] b = new byte[is.available()];
            is.read(b);
            //使用哈夫曼进行编码，获取编码表
            //直接对源文件压缩
            byte[] huffmanBytes = huffmanZip(b);
            //创建文件的输出流，存放压缩文件
            os = new FileOutputStream(dstFile);
            oos = new ObjectOutputStream(os);
            //以对象流的方式写入哈夫曼的编码，为了以后解压的时候使用。
            oos.writeObject(huffmanBytes);
            oos.writeObject(humanCodes);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                is.close();
                os.close();
                oos.close();
            } catch (IOException e) {


            }
        }
    }

    //编写一个方法实现对压缩文件的解压
    public static void unZipFile(String zipFile,String dstFile){
         //定义文件的输入流
        InputStream is = null;
        //输入流关联的对象流
        ObjectInputStream ois = null;
       //输出流
        OutputStream os = null;

        try {
            //创建文件输入流
            is = new FileInputStream(zipFile);
            //创建关联的对象输入流
            ois = new ObjectInputStream(is);
           byte[] huffmanBytes = (byte[])ois.readObject();
           Map<Byte,String> huffmanCodes = (Map<Byte,String>)ois.readObject();

           //解码
            byte[] bytes = decode(huffmanCodes,huffmanBytes);
            os = new FileOutputStream(dstFile);
            //写出数据到文件中
            os.write(bytes);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            try {
                os.close();
                ois.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //编写一个方法对压缩数据的解码
    private static byte[] decode(Map<Byte,String> huffmanCode,byte[] huffmanBytes){
        /*
        * 1.先得到byte数组的字符串
        * */
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < huffmanBytes.length; i++) {
            boolean flag = (i==huffmanBytes.length-1);
            stringBuilder.append(byteToString(!flag,huffmanBytes[i]));
        }
        //反向拿到对应的查找值
        Map<String,Byte> map = new HashMap<>();
        for (Map.Entry<Byte,String> entry : huffmanCode.entrySet()){
            map.put(entry.getValue(),entry.getKey());
        }
        //创建一个集合存放byte
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length();) {
            int count = 1;//计数器
            boolean flag = true;
            Byte b = null;
            while (flag){
                //取出一个1或0；
                String key = stringBuilder.substring(i,i+count);//让count走知道匹配到有个字符
                b = map.get(key);
                if (b==null){
                    count++;
                }else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;//i直接移动到count位置。
        }
        //当for循环结束的时候，list中存放了所有的字符。
        byte[] b = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;
    }

    /*
    * 完成数据的解压：
    * 思路：
    * 1、先重新转换成字符串一个赫夫曼编码对应的二进制的字符串
    * 2、将赫夫曼编码对应的二进制字符串对照赫夫曼编码转化为字符串
    * */
    //将一个byte转换为二进制的字符串
    private static String byteToString(Boolean flag,byte b){
        int tmp = b;
        //这个地方返回的是tmp二进制对应的补码
        //整数需要补高位
        if (flag){
            tmp |= 256;
        }
       //按位与256 ：1 0000 0000
        String s = Integer.toBinaryString(tmp);
       if (flag){
           return s.substring(s.length()-8);
       }else {
           return s;
       }
    }

    //原始的字符串转换的byte;
    private static byte[] huffmanZip(byte[] bytes){
        List<Node> getnodes = getnodes(bytes);
        Node huffmanTree = createHuffmanTree(getnodes);
        Map<Byte, String> codes = getCodes(huffmanTree);
        byte[] zip = zip(bytes, codes);
        return zip;
    }

    //编写一个方法，将一个字符串对应的byte数组通过生成的Huffman编码表，
    //返回压缩后的byte数组
    private static byte[] zip(byte[] bytes,Map<Byte,String> humanCodes){
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : bytes) {
            stringBuilder.append(humanCodes.get(b));
        }

        int len = (stringBuilder.length()+7) / 8;
        //创建一个存储压缩后的byte数组
        byte[] huffmancodeBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i+=8) {
            String strByte;//每8位对应一个byte
            if (i+8>stringBuilder.length()){
               strByte = stringBuilder.substring(i);
            }else {
              strByte = stringBuilder.substring(i,i+8);
            }
            huffmancodeBytes[index] = (byte)Integer.parseInt(strByte,2);
            index++;
        }
        return huffmancodeBytes;
    }


    private static void preOrder(Node root){
        if (root!=null){
            root.preOrder();
        }else {
            System.out.println("空树。");
        }
    }
    //调用重载
    private static Map<Byte,String> getCodes(Node root){
        if (root == null){
            return null;
        }
        //处理左子树
        getCodes(root.left,"0",stringBuilder);
        //柚子树
        getCodes(root.right,"1",stringBuilder);
        return humanCodes;
    }

    //将赫夫曼编码表存放在Map中比较合适：
    //在生成赫夫曼编码表时，需要拼接路径，存储某个叶子节点的路径
    static Map<Byte,String> humanCodes = new HashMap<>();
    static StringBuilder stringBuilder = new StringBuilder();
    //将传入的node节点的所有叶子节点的哈夫曼编码得到。放入到集合中
    //code左子节点0，右子节点1
    private static void getCodes(Node node,String code,StringBuilder stringBuilder){
        StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
        stringBuilder2.append(code);
        if (node!=null) {
            //判断当前node是否为叶子节点
            if (node.data == null) {//非叶子节点
                //向左递归
                getCodes(node.left,"0",stringBuilder2);
                //向右递归
                getCodes(node.right,"1",stringBuilder2);
            }else {//叶子节点
                humanCodes.put(node.data,stringBuilder2.toString());

            }
        }
    }

    private static List<Node> getnodes(byte[] bytes){
        ArrayList<Node> nodes = new ArrayList<>();
        //存储每一个byte出现的次数。用map合适
        HashMap<Byte, Integer> counts = new HashMap<>();
        for (byte b : bytes) {
            Integer count = counts.get(b);
            if (count==null){
                counts.put(b,1);
            }else {
                counts.put(b,count+1);
            }
        }
        for (Map.Entry<Byte,Integer> entry : counts.entrySet()){
            nodes.add(new Node(entry.getKey(),entry.getValue()));
        }
        return nodes;
    }

    //通过list构建hehuman树
    private static Node createHuffmanTree(List<Node> nodes){
        while (nodes.size()>1){
            Collections.sort(nodes);
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            //创建一个根节点，没有data，有权重
            Node root = new Node(null,left.weight+right.weight);
            root.left = left;
            root.right = right;
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(root);
        }
        return nodes.get(0);
    }
}

//创建node带数据和权值
class Node implements Comparable<Node>{
    Byte data;//存放数据本身
    int weight;
    Node left;
    Node right;
    public Node(Byte data,int weight){
        this.data = data;
        this.weight = weight;
    }

    @Override
    public int compareTo(Node o) {
        return this.weight-o.weight;
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }
    //前序遍历
    public void preOrder(){
        System.out.println(this);
        if (this.left!=null){
            this.left.preOrder();
        }
        if (this.right!=null){
            this.right.preOrder();
        }
    }
}
